<script lang="ts" setup name="LoginForm">
import { ref, watch } from 'vue'
import { useField, useForm } from 'vee-validate'
import Message from '@/components/message'
import useStore from '@/store'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
import { useCountDown } from '@/utils/hooks'
import { accountRule, passwordRule, isAgreeRule, mobileRule, codeRule } from '@/utils/validate'
const router = useRouter()
const route = useRoute()
const { user, cart } = useStore()
const active = ref(1)
// 验证码
// const time = ref(0)

// const form = ref({
//   account: 'xiaotuxian001',
//   password: '123456',
//   isAgree: true
// })

// const login = async () => {
//   // 常规写法
//   if (form.value.account === '') {
//     // Message({ type: 'error', text: '用户名或手机号不能为空' })
//     Message.error('用户名或手机号不能为空')
//     return
//   }
//   if (form.value.password === '') {
//     Message({ type: 'error', text: '密码不能为空' })
//     return
//   }
//   if (!form.value.isAgree) {
//     Message({ type: 'error', text: '请同意许可' })
//     return
//   }
//   try {
//     await user.reqLogin(form.value.account, form.value.password)
//     Message({ type: 'success', text: '登录成功' })
//     // 跳转到首页
//     router.push('/')
//   } catch {
//     Message.error('用户名或者密码错误')
//   }
// }

// 表单校验
const { validate, resetForm } = useForm({
  // 提供校验规则    =>规则抽离了，可以在其他地方使用
  // validationSchema: {
  //   // if(active:number){
  //   // }
  //   account: (value: string) => {
  //     // 校验的value值
  //     // value是将来使用该规则的表单元素的值
  //     // 1. 必填
  //     // 2. 6-20个字符，需要以字母开头
  //     // 如何反馈校验成功还是失败，返回true才是成功，其他情况失败，返回失败原因。
  //     if (!value) return '请输入用户名'
  //     if (!/^[a-zA-Z]\w{5,19}$/.test(value)) return '字母开头且6-20个字符'
  //     return true
  //   },
  //   password: (value: string) => {
  //     if (!value) return '请输入密码'
  //     if (!/^\w{6,12}$/.test(value)) return '密码必须是6-24位字符'
  //     return true
  //   },
  //   isAgree: (value: boolean) => {
  //     if (!value) return '请同意隐私条款'
  //     return true
  //   },
  //   mobile: (value: string) => {
  //     if (!value) return '请输入手机号'
  //     if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'
  //     return true
  //   },
  //   code: (value: string) => {
  //     if (!value) return '请输入验证码'
  //     if (!/^\d{6}$/.test(value)) return '验证码格式错误'
  //     return true
  //   }
  // },
  validationSchema: {
    account: accountRule,
    password: passwordRule,
    isAgree: isAgreeRule,
    mobile: mobileRule,
    code: codeRule
  },
  // 提供初始值
  initialValues: {
    account: 'cdshi0006',
    password: '123456',
    mobile: '13012345683',
    code: '123456',
    isAgree: true
  }
})
// const { value, errorMessage } = useField('account')
const { value: account, errorMessage: accountError } = useField<string>('account')
const { value: password, errorMessage: passwordError } = useField<string>('password')
const { value: isAgree, errorMessage: isAgreeError } = useField<boolean>('isAgree')
const { value: mobile, errorMessage: mobileError, validate: validateMobile } = useField<string>('mobile')
const { value: code, errorMessage: codeError } = useField<string>('code')
// 监听 active 的变化
watch(active, () => {
  // 重置表单
  resetForm()
})
// 获取验证码
// const getCode = async () => {
//   if (time.value) return
//   time.value = 60
//   const timerId = setInterval(() => {
//     time.value--
//     if (!time.value) {
//       // 清除定时器
//       clearInterval(timerId)
//     }
//   }, 1000)
//   await user.reqGetCode('13012345683', 'login')
//   Message.success('发送成功')
// }
const mobileRef = ref<HTMLInputElement | null>(null)
const { time, start } = useCountDown(60)
const getCode = async () => {
  if (time.value) return

  const res = await validateMobile()
  if (!res.valid) {
    // 校验没通过
    mobileRef.value?.focus()
    return
  }
  // 通过 =>
  try {
    await user.reqGetCode(mobile.value, 'login')
    Message.success('发送成功')
  } catch {
    return
  }

  // time.value = 60
  // const timerId = setInterval(() => {
  //   time.value--
  //   if (!time.value) {
  //     // 清除定时器
  //     clearInterval(timerId)
  //   }
  // }, 1000)
  //
  // 开启 倒计时
  start()
}

// 登录
const login = async () => {
  const res = await validate()
  // console.log(res)
  if (!res.valid) return
  // try {
  if (active.value) {
    // 账号登录
    if (res.errors.account || res.errors.password || res.errors.isAgree) return
    await user.reqLogin(account.value, password.value)
  } else {
    // 验证码登录
    if (res.errors.mobile || res.errors.code || res.errors.isAgree) return
    await user.mobileLogin(mobile.value, code.value)
  }
  // 登录成功后，合并购物车
  cart.mergeLocalCart()
  Message.success('登录成功')
  // 判断有没有name属性
  // if (route.query.name) return router.push(route.query.name as string)
  // router.push('/')

  router.push((route.query.name as string) || '/')

  // } catch (error) {
  //   // console.log(error)
  //   if (active.value) Message.error('账号或者密码错误')
  //   else Message.error('验证码错误')
  // }
}
</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="active = 1" href="javascript:;" v-if="!active">
        <i class="iconfont icon-user"></i>
        使用账号登录
      </a>
      <a @click="active = 0" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i>
        使用短信登录
      </a>
    </div>
    <div class="form">
      <!-- 账号登录 -->
      <template v-if="active">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input v-focus type="text" placeholder="请输入用户名或手机号" v-model="account" />
          </div>
          <div class="error" v-if="accountError">
            <i class="iconfont icon-warning" />
            {{ accountError }}
          </div>
          <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input type="password" placeholder="请输入密码" v-model="password" />
          </div>

          <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />
            {{ passwordError }}
          </div>
        </div>
      </template>

      <!-- 手机号登录 -->

      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input ref="mobileRef" v-focus type="text" placeholder="请输入手机号" v-model="mobile" />
          </div>
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />
            {{ mobileError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="password" placeholder="请输入验证码" v-model="code" />
            <span class="code" @click="getCode">{{ time === 0 ? '发送验证码' : `${time}s后获取` }}</span>
          </div>
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />
            {{ codeError }}
          </div>
        </div>
      </template>

      <div class="form-item">
        <div class="agree">
          <!-- <input class="checked" type="checkbox" name="" id="" /> -->
          <!-- <XtxCheckbox v-model:checked="form.isAgree" /> -->
          <XtxCheckbox v-model:checked="isAgree">我已同意</XtxCheckbox>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeError">
          <i class="iconfont icon-warning" />
          {{ isAgreeError }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <!-- <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="" /> -->

      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="QQ登录" border="0" />
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
